# -*- coding:utf-8 -*-
'''
# Author: xiguan
# Mail: xiguan.teng@qq.com
# -----
# Last Modified: 2022-05-13 09:50:25
# Modified By: xiguan
# -----
# Copyright (c) 2022 XiGuan Inc.
# 
# No Bug No error No warning.
# -----
'''

import json
import os
import time
from os import listdir
from pickle import dump, dumps, loads

from flask import Blueprint, jsonify, request, session

from config import db_session, engine
from entity.Ignore import Ignore
from entity.LocalFile import LocalFile
from entity.Sync import Sync

syncdir = Blueprint('syncdir',__name__)

# 将忽略列表对象转化为 json 格式
def syncdir_2_json(obj):
   return {
      "id": obj.id,
      "port": obj.port,
      "path": obj.path,
      "uid": obj.uid
   }

# 将文件对象转化为 json 格式
def myfile_2_json(obj):
   return {
      "name": obj.name,
      "type": obj.type,
      "size": obj.size,
      "mtime": obj.mtime,
      "ctime": obj.ctime
   }

@syncdir.route("/get_all", methods=['GET'])
def get_all():
   print("sync get_all success call")
   user = loads(session.get("user"))
   # print(type(user))
   syncdirs = list(db_session.query(Sync).filter_by(uid = user.id).order_by("id"))
   return json.dumps(syncdirs, default=syncdir_2_json)

@syncdir.route('/add_dir/')
def add_dir():
   try:
      user = loads(session.get("user"))
      path = request.args.get('path')
      port = request.args.get('port')
      # 创建一个新的对象
      add_syncdir = Sync(path=path, port=port, uid=user.id)
      # 向数据库中创建用户
      db_session.add(add_syncdir)
      # 提交
      db_session.commit()
   except Exception:
      return "NO"
   return "OK"

# 删除同步目录
@syncdir.route('/del_dir/')
def del_dir():
   try:
      id = request.args.get('id')
      with engine.connect() as con:
         execute_string = "delete from ftp_server.syncdir where `id` =" + str(id)
         con.execute(execute_string)
         db_session.commit()
   except Exception:
      return "NO"
   return "OK"

# 获取本地同步目录详情
@syncdir.route('/get_sync_detail/')
def get_syncdir_detail():
   print("sync get_sync_detail success call")
   # 本地同步目录编号
   id = request.args.get('id')
   # 获取本地路径
   user = loads(session.get("user"))
   # 获取同步目录对象
   syncdirs = list(db_session.query(Sync).filter_by(uid = user.id, id=id))
   # 获取路径
   if len(syncdirs) == 0:
      return json.dumps([], default=myfile_2_json)
   path = syncdirs[0].path
   # 读取路径下内容
   syncdir_list = listdir(path)
   # 返回到前端的对象数组
   myfile_list = []
   # 遍历文件
   for file in syncdir_list:
      if os.path.isdir(path + "/" + file):
         name = file
         type = "文件夹"
         size = os.path.getsize(path + "/" + file)
      else:
         name = file
         temp, type = os.path.splitext(file)
         type = type + "文件"
         size = os.path.getsize(path + "/" + file)
      mtime = os.path.getmtime(path + "/" + file)
      ctime = os.path.getctime(path + "/" + file)
      mtime_array = time.localtime(mtime)
      ctime_array = time.localtime(ctime)
      mstyle_time = time.strftime("%m/%d %H:%M", mtime_array)
      cstyle_time = time.strftime("%m/%d %H:%M", ctime_array)

      myfile = LocalFile(name=name, type=type, size=size, mtime=mstyle_time, ctime=cstyle_time)
      myfile_list.append(myfile)
   return json.dumps(myfile_list, default=myfile_2_json)